#!/bin/bash

###############################################################################
# Spring Boot 应用状态检查脚本
# 项目名称: enterprise-portal
###############################################################################

# 应用配置
APP_NAME="enterprise-portal"
APP_PORT=8091

# 获取脚本所在目录
cd "$(dirname "$0")" || exit 1
BASE_DIR=$(pwd)
PID_FILE="$BASE_DIR/$APP_NAME.pid"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_header() {
    echo -e "${BLUE}=================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}=================================${NC}"
}

print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查应用状态
print_header "应用状态检查"

# 检查PID文件
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    print_info "PID文件存在: $PID_FILE"
    print_info "记录的PID: $PID"

    # 检查进程是否运行
    if ps -p "$PID" > /dev/null 2>&1; then
        print_info "进程状态: 运行中"

        # 显示进程详情
        echo ""
        print_header "进程详情"
        ps aux | grep "$PID" | grep -v grep

        # 显示资源占用
        echo ""
        print_header "资源占用"
        echo "CPU和内存占用:"
        ps -p "$PID" -o pid,pcpu,pmem,vsz,rss,cmd

        # 显示线程数
        THREAD_COUNT=$(ps -Lp "$PID" | wc -l)
        print_info "线程数: $((THREAD_COUNT - 1))"

    else
        print_error "进程状态: 未运行（PID文件已过期）"
    fi
else
    print_warn "PID文件不存在: $PID_FILE"
fi

# 检查端口监听
echo ""
print_header "端口监听检查"

if command -v netstat &> /dev/null; then
    PORT_INFO=$(netstat -tlnp 2>/dev/null | grep ":$APP_PORT ")
elif command -v ss &> /dev/null; then
    PORT_INFO=$(ss -tlnp 2>/dev/null | grep ":$APP_PORT ")
fi

if [ -n "$PORT_INFO" ]; then
    print_info "端口 $APP_PORT 正在监听"
    echo "$PORT_INFO"
else
    print_error "端口 $APP_PORT 未监听"
fi

# 检查应用健康状态
echo ""
print_header "应用健康检查"

# 尝试访问健康检查端点（如果有）
if command -v curl &> /dev/null; then
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$APP_PORT/actuator/health 2>/dev/null)
    if [ "$HTTP_CODE" = "200" ]; then
        print_info "健康检查: 正常 (HTTP $HTTP_CODE)"
    else
        # 尝试访问根路径
        HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$APP_PORT/ 2>/dev/null)
        if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ] || [ "$HTTP_CODE" = "404" ]; then
            print_info "服务响应: 正常 (HTTP $HTTP_CODE)"
        else
            print_warn "服务响应: 异常或未就绪 (HTTP $HTTP_CODE)"
        fi
    fi
else
    print_warn "未安装curl，跳过健康检查"
fi

# 显示最近的日志
LOG_FILE="$BASE_DIR/logs/application.log"
if [ -f "$LOG_FILE" ]; then
    echo ""
    print_header "最近10行日志"
    tail -n 10 "$LOG_FILE"
fi

echo ""
print_header "检查完成"
